'use strict';
let router = require('koa-router')();
let path = require('path');
let fs = require('fs');

function searchControllerFile() {
    let file = fs.readdirSync(__dirname);
    let controllers = file.filter((fileName) => {
        return fileName.endsWith('.js') && fileName !== 'hello.js'
    });

    return controllers;
}

function registerControllerFile(files) {
    files.forEach(item => {
        let resultPath = path.join(__dirname, item);
        let routerObj = require(resultPath);
        for (var key in routerObj) {
            let type = routerObj[key][0];
            let fn = routerObj[key][1];
            if (type === 'get') {
                router.get(key, fn)
            } else {
                router.post(key, fn)
            }
        }
    })
}

module.exports = (dir) => {
    let defaultDir = dir || '/controllers';

    let root = path.resolve('.');

    let pointPath = path.join(defaultDir,root);

    let file = searchControllerFile(pointPath);

    registerControllerFile(file);

    return router.routes();
}